<?php

namespace addons\crontab\controller;

use addons\unishop\model\Product;
use app\admin\model\Admin;
use app\common\model\User;
use think\Controller;
use think\Log;

/**
 * /usr/bin/php  /www/wwwroot/hxyp.11taotao.com/public/index.php  /addons/crontab/water/inject > /dev/null  2>&1 &
 * 刷数据
 * @internal
 */
class Water extends Controller
{

    /**
     * 初始化方法,最前且始终执行
     */
    public function _initialize()
    {
        // 只可以以cli方式执行
        if (!$this->request->isCli()) {
            $this->error('Water script only work at client!');
        }

        parent::_initialize();

        // 清除错误
        error_reporting(0);
        // 设置永不超时
        set_time_limit(0);
    }

    /**
     * 根据指定的日期 以及金额注入数据
     * 1、15 的抽成 打包费  0-3元  运费 2-10
     * */
    public function inject()
    {
//        echo '232323';
//        $startDate = '2023-12-27';
//        $endDate = '2024-01-01 23:59:59';
        $startDate=date("Y-m-d",strtotime('-1 day')).' 00:00:00';
        $endDate=date("Y-m-d",strtotime('-1 day')).' 23:59:59';
        echo "开始时间:" . $startDate . " 结束时间:" . $endDate . PHP_EOL;
        //$allAmount = 1441500;
        $allAmount=15300;
        echo "总共营业额:" . $allAmount . PHP_EOL;
        $days = ceil((strtotime($endDate) - strtotime($startDate)) / 86400); //天数
        echo "总天数:" . $days . PHP_EOL;
        $dailyAmount = ceil($allAmount / $days);
        $dailyAmount=rand($dailyAmount-rand(100,300),$dailyAmount+rand(100,300));
        echo "日营业额:" . $dailyAmount . PHP_EOL;
        $moneyUp = 55;
        echo "单个订单上限:" . $moneyUp . PHP_EOL;
        $moneyDown = 25;
        echo "单个订单下限:" . $moneyDown . PHP_EOL;
        if ($days) {
            for ($i = 0; $i < $days; $i++) {
                echo "当前:" . $i . "######".PHP_EOL;
                $todayTimeStamp = strtotime($startDate) + $i * 86400;
                $today = date("Y-m-d", $todayTimeStamp);
                echo "当前日期:" . $today . "######".PHP_EOL;
                $dataParams = [
                    'dailyAmount' => $dailyAmount,
                    'today' => $today,
                    'moneyUp' => $moneyUp,
                    'moneyDown' => $moneyDown
                ];
                try {
                    $this->genOrderData($dataParams);
                } catch (\Exception $e) {
                    $code = $e->getCode();
                    $message = $e->getMessage();
                    $msg = "处理异常|code:" . $code . "|message:" . $message;
                    Log::error($msg);
                }
            }
        }
    }

    /**
     *  1、15 的抽成 打包费  0-3元  运费 2-10
     * @param $dataParams
     * @throws \Exception
     */
    public function genOrderData($dataParams = [])
    {
        $dailyAmount = $dataParams['dailyAmount'] ?? 0; //每天营业额
        $today = $dataParams['today'] ?? date('Y-m-d');
        $moneyUp = $dataParams['moneyUp'] ?? 0;
        $moneyDown = $dataParams['moneyDown'] ?? 0;
        $orderTotal = 0;
        do {
            //订单生成时间 区间  06:00:00  20:59:59
            $startHour = '06:00:00';
            $endHour = '20:59:59';
            $minTime = strtotime($today . " " . $startHour);
            $maxTime = strtotime($today . " " . $endHour);
            $genCreatedAt = date("Y-m-d H:i:s", rand($minTime, $maxTime));
           // $commissionRates = [1, 15];
            $boxFee = floatval(rand(0, 3));
            $deliveryFee = floatval(rand(2, 10));
            $result=hitRate();
            $discount=0;
            if($result){
                $hitName=$result['name']??'没中奖';
                if($hitName!='没中奖'){
                    $discount=5;
                }
            }
            $discount=floatval($discount);
            //$commissionRateKey = array_rand($commissionRates, 1);
            $commissionRate = 15;
            //获取随机商品
            $goodsPrices=[9.90,10.00,46.00,43.00,42.00,42.00,43.00,37.00,37.00,38.00,45.00,47.00,42.00,48.00,88.00,88.00,18.00,25.00,10.00,98.00,38.00,12.00,26.00,18.00,20.00,118.00,28.00,10.00,28.00,18.00,28.00,68.00,38.00,98.00,98.00,128.00,68.00,138.00,78.00,138.00,48.00,98.00,68.00,118.00,18.00,38.00,15.00,16.00,23.00,28.00,79.00,109.00,29.00];
            $randGoodPriceKey=array_rand($goodsPrices,1);
            $goods_price=$goodsPrices[$randGoodPriceKey];
            // = rand($moneyDown, $moneyUp);
            $money=$goods_price;
            $amount=1;
            $good=Product::where('sales_price','=',$goods_price)->find();
            $sale_price=$good['sales_price']??0;
            if($goods_price<$moneyDown){
                $money=$goods_price*3;
                $amount=3;
            }
            $good_id=$good['id'];
            $good_name=$good['goods_name'];
            $boxFee=$good['boxes_price']??$boxFee;
            $receivable=$boxFee+$deliveryFee+$money;
            $dailyAmount = $dailyAmount - $receivable;
            if ($dailyAmount <= $moneyDown) {
                continue;
            }
            $received=$receivable-$discount;
            $commissionMoney = sprintf('%.2f', $money * ($commissionRate / 100));
            $deliveryDate = date("Y-m-d", strtotime($today));
            $deliveryStart = date("Y-m-d H:i", strtotime($today)) . ':00';
            $deliveryEnd = $deliveryStart;
            $orderNo = genOrderNo($genCreatedAt);
            $pay_time = date("Y-m-d H:i:s", strtotime($genCreatedAt) + rand(60, 180)); //订单创建 1-3分钟完成支付
            $genModifiedAt = date("Y-m-d H:i:s", strtotime($pay_time) + rand(1200, 2400)); // 支付完成之后  20-40分钟 完成配送
            $station_id = 240;
            $station = Station::where('id', '=', $station_id)->find();
            if ($station) {
                $station_name = $station['name'];
                $township_id=$station['township_id'];
                $station_id=$station['id'];
            }else{
                $station_name = '闫鑫店铺';
                $township_id=1;
                $station_id=2;
            }
            $user_id=rand(3,10120);
            $user=User::where('id','=',$user_id)->find();
            if(!$user){
                $user_id=3;
            }
            $addressIds=Address::where('user_id','=',$user_id)->column('id');
            $address_id=1;
            if($addressIds){
                $addressKey=array_rand($addressIds,1);
                $address_id=$addressIds[$addressKey];
            }
            echo "剩余金额:" . $dailyAmount . PHP_EOL;
            $orderTotal++;
            echo $orderTotal.PHP_EOL;
            $orderData = [
                'code' => $orderNo,
                'order_status' => 9,
                'pay_status' => 2,
                'pay_time' => $pay_time,
                'address_id' => $address_id,
                'township_id' => $township_id,
                'station_id' => $station_id,
                'station_name' => $station_name,
                'user_id' => $user_id,
                'delivery_date' => $deliveryDate,
                'delivery_start' => $deliveryStart,
                'delivery_end' => $deliveryEnd,
                'coupons_id' => 0,
                'activity_id' => 0,
                'boxes_fee' => $boxFee,
                'delivery_fee' => $deliveryFee,
                'money' => $money,
                'receivable' => $receivable,
                'discount' => $discount,
                'refund_price' => 0.00,
                'person_num'=>1,
                'received' => $received,
                'commission_rate' => $commissionRate,
                'commission_money' => $commissionMoney,
                'gmt_created' => $genCreatedAt,
                'gmt_modified' => $genModifiedAt,
            ];
            $biOrderModel=new BiOrder();
            $orderId=$biOrderModel->insertGetId($orderData);
            if(!$orderId){
                $message="Error creating order|".var_export($biOrderModel->getError(),true);
                echo $message.PHP_EOL;
                Log::error($message);
            }
            $orderDetailData=[
                'order_id'=>$orderId,
                'order_code'=>$orderNo,
                'station_id'=>$station_id,
                'goods_id'=>$good_id,
                'goods_specs_id'=>'[]',
                'goods_name'=>$good_name,
                'price'=>$sale_price,
                'money'=>$goods_price,
                'amount'=>$amount,
                'boxes_price'=>$boxFee,
                'discount_nums'=>1,
                'discount_money'=>$discount,
                'food_price_total'=>$money,
                'gmt_created'=>$genCreatedAt,
                'gmt_modified'=>$genCreatedAt
            ];
            $biOrderDetaioModel=new BiOrderDetail();
            if(!$biOrderDetaioModel->insert($orderDetailData)){
                $message="Error creating order_detail|".var_export($biOrderDetaioModel->getError(),true);
                echo $message.PHP_EOL;
                Log::error($message);
            }
            $deliveryData=[
                'order_id'=>$orderId,
                'delivery_fee'=>$deliveryFee,
                'station_id'=>$station_id,
                'deliveryer_id'=>10,
                'order_created'=>$genCreatedAt,
                'status'=>4,
                'arrived_at'=>$genModifiedAt,
                'gmt_created'=>$genCreatedAt,
                'gmt_modified'=>$genModifiedAt
            ];
            $biDeliveryModel=new BiDelivery();
            if(!$biDeliveryModel->insert($deliveryData)){
                $message="Error creating order_detail|".var_export($biDeliveryModel->getError(),true);
                echo $message.PHP_EOL;
                Log::error($message);
            }
            //
        } while ($dailyAmount > 0);
        echo "今日订单数:" . $orderTotal . PHP_EOL;
    }

    /**
     * 更新店铺经纬度
     * */
    public function store()
    {
        $stations=Station::all();
        if($stations){
            foreach ($stations as $station){
                $township_id=$station['township_id'];
                $station_id=$station['id'];
                $lat=$station['lat'];
                $lng=$station['lng'];
                if(!$lng || !$lat){
                    $message="无经纬度:".$station_id;
                    echo $message.PHP_EOL;
                    Log::error($message);
                    continue;
                }
                $adminUser=Admin::where('station_id','=',$station_id)->findOrFail();
                if(!$adminUser){
                    $message="无管理员:".$station_id;
                    echo $message.PHP_EOL;
                    Log::error($message);
                    continue;
                }
                $user_id=$adminUser['id']??0;
                $syncData=[
                    'lng'=>$lng,
                    'lat'=>$lat,
                    'client'=>'store',
                    'user_id'=>$user_id,
                    'township_id'=>$township_id
                ];
                UserService::syncPos($syncData);
                sleep(1);
                echo $lat."|".$lng."|更新数据:".var_export($syncData,true).PHP_EOL;
            }
        }
    }


}
